XLEN=64
ISA=imac
FPGA_BOARD_ALIAS=arty100t

export RISCV_PREFIX=riscv$(XLEN)-unknown-elf-
export RISCV_GCC=$(RISCV_PREFIX)gcc
export RISCV_OBJDUMP=$(RISCV_PREFIX)objdump
export RISCV_GCC_OPTS=-mcmodel=medany -static -std=gnu99 -O2 -ffast-math -fno-common -fno-builtin-printf -DCUSTOM
export RISCV_LINK_OPTS=-w -static -nostdlib -nostartfiles -lm -lgcc
export RISCV_INC= -I$(PWD)/common/
export PROGRAMS_DIR=programs/
export RISCV_MARCH=rv$(XLEN)$(ISA)
export BUILD=$(PWD)/build/
export RISCV_LINK=$(PWD)/common/ddrlink.ld

$(BUILD)/crt_boot.o:
	@ mkdir -p $(BUILD)/
	@$(RISCV_GCC) -g $(RISCV_GCC_OPTS) $(RISCV_LINK_OPTS) $(RISCV_INC) -march=$(RISCV_MARCH) \
		 -c common/crt_boot.S -o $(BUILD)/crt_boot.o
$(BUILD)/crt.o:
	@ mkdir -p $(BUILD)/
	@$(RISCV_GCC) -g $(RISCV_GCC_OPTS) $(RISCV_LINK_OPTS) $(RISCV_INC) -march=$(RISCV_MARCH) \
		 -c common/crt.S -o $(BUILD)/crt.o
$(BUILD)/syscalls.o:
	@ mkdir -p $(BUILD)/
	@$(RISCV_GCC) -g $(RISCV_GCC_OPTS) $(RISCV_LINK_OPTS) $(RISCV_INC) -march=$(RISCV_MARCH) \
		 -c common/syscalls.c -o $(BUILD)syscalls.o

PROGRAM?=hello

.PHONY: list-programs
list-programs: 
	@ echo program-list: $(shell ls $(PROGRAMS_DIR)/)

.PHONY: boot
boot: export RISCV_BOOT_LINK=$(PWD)/common/bootlink.ld
boot: $(BUILD)/syscalls.o $(BUILD)/crt_boot.o
	@ echo "Compiling boot"
	@ cd $(PROGRAMS_DIR)/boot; $(MAKE)
	@ elf2hex 4 1024 $(BUILD)/boot 65536 > $(BUILD)/boot.mem

.PHONY: ocmhex
ocmhex:	export RISCV_LINK=$(PWD)/common/ocmlink.ld
ocmhex: $(BUILD)/crt.o $(BUILD)/syscalls.o
ifneq ("$(wildcard $(ELF))","")
	@ echo "Loading $(ELF)"
	@ elf2hex 4 4096 $(ELF) 268435456 > $(BUILD)/ocm.mem
else 
	@ echo "Compiling $(PROGRAM)"
	@ cd $(PROGRAMS_DIR)/$(PROGRAM); $(MAKE)
	@ echo "Generating hex for $(BUILD)/$(PROGRAM) at OCM"
	@ elf2hex 4 4096 $(BUILD)/$(PROGRAM) 268435456 > $(BUILD)/ocm.mem
endif

.PHONY: ddrhex
ddrhex: $(BUILD)/crt.o $(BUILD)/syscalls.o
ifneq ("$(wildcard $(ELF))","")
	@ echo "Loading $(ELF)"
	@ elf2hex 8 4194304 $(ELF) 2147483648 > $(BUILD)/ddr.mem
else 
	@ echo "Compiling $(PROGRAM)"
	@ cd $(PROGRAMS_DIR)/$(PROGRAM); $(MAKE)
	@ echo "Generating hex for $(BUILD)/$(PROGRAM) at DDR"
	@ elf2hex 8 4194304 $(BUILD)/$(PROGRAM) 2147483648 > $(BUILD)/ddr.mem
endif

.PHONY: connect_gdb
connect_gdb: $(BUILD)/crt.o $(BUILD)/syscalls.o
ifneq ("$(wildcard $(ELF))","")
	@ echo "Loading $(ELF)"
	./debug_script.sh --elf $(ELF) --openocd-config ../fpga/$(FPGA_BOARD_ALIAS)/ocd.cfg  
else 
	@ echo "Compiling $(PROGRAM)"
	@ cd $(PROGRAMS_DIR)/$(PROGRAM); $(MAKE)
	@ echo "Loading $(BUILD)/$(PROGRAM)"
	@ ./debug_script.sh --elf $(BUILD)/$(PROGRAM) --openocd-config ../fpga/$(FPGA_BOARD_ALIAS)/ocd.cfg  
endif

.PHONY clean:
clean:
	rm -rf $(BUILD)
